package io;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class Clent2 extends Thread {
    public static void main(String[] args) throws InterruptedException {
        new Clent2().start();
        Thread.sleep(20 * 1000);
    }

    @Override
    public void run() {
        try (Selector selector = Selector.open();) {
            SocketChannel socketChannel = SocketChannel.open();
//            socketChannel.bind(new InetSocketAddress(InetAddress.getLocalHost(), 8989));
            socketChannel.connect(new InetSocketAddress(InetAddress.getLocalHost(), 8989));
            socketChannel.configureBlocking(false);
//            socketChannel.register(selector, SelectionKey.OP_READ);
//            socketChannel.register(selector, SelectionKey.OP_READ);
//            socketChannel.register(selector, SelectionKey.OP_CONNECT);

            ByteBuffer buffer = ByteBuffer.allocate(100);
            while (socketChannel.read(buffer) > 0) {
                System.out.println("read");
                buffer.flip();
                while (buffer.hasRemaining()){
                    System.out.println(Charset.defaultCharset().decode(buffer));
                }

                buffer.clear();
//                Thread.sleep(1000);
            }

//            socketChannel.register(selector, SelectionKey.OP_WRITE);
//            Socket client = new Socket(InetAddress.getLocalHost(), SocketBIOTest.CountDownServer.port);
//            client.getChannel().register(selector, SelectionKey.OP_READ);
//            ByteBuffer buffer = ByteBuffer.allocate(1024);
//            while (true) {
//                selector.select();
//                Set<SelectionKey> keys = selector.selectedKeys();
//                for (SelectionKey key : keys) {
//                    System.out.println(key.interestOps());
//                    if (key.interestOps() == SelectionKey.OP_READ ){
//                        SocketChannel channel = (SocketChannel) key.channel();
//                        channel.read(buffer);
//                        System.out.println("read");
//                        buffer.flip();
//
//                        System.out.println(buffer.asCharBuffer());
//                        buffer.clear();
//                    }
//                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
